cap log close
use "../employers/temp/firmfe_value_split_all3stack", clear // using data from employers folder

gen year_entry = floor(window/10)

merge m:1 betnr using "$temp/wz_bula.dta"

drop if _merge == 2
drop _merge

gen var_err = .

forvalues y = 1999(3)2017 {
	forvalues b = 1/ 16 {

corr firm_fe1 firm_fe2 if `y' == year_entry & `b' == bula, covariance
local cov_fe = r(cov_12)

* compute varianze of firm fixed effects
sum firm_fe2 if `y' == year_entry & `b' == bula
local var_fe = r(Var)

* compute varianze of error
replace var_err = `var_fe' - `cov_fe' if `y' == year_entry & `b' == bula

	}
}

keep if !missing(bula)
duplicates drop year_entry bula, force

rename bula region_entry 
merge 1:1 region_entry year_entry using "$temp\U_internal.dta", keepusing(U_internal)
drop if _merge == 2
drop _merge
rename region_entry bula
rename year_entry year

cap log close
log using "$log/11_measurement_error_check_$S_DATE", text replace

egen std_var_err = std(var_err)

reghdfe var_err U_internal, vce(cluster bula)
reghdfe var_err U_internal, absorb(bula) vce(cluster bula)
reghdfe var_err U_internal, absorb(bula year) vce(cluster bula)

reghdfe std_var_err U_internal, vce(cluster bula)
reghdfe std_var_err U_internal, absorb(bula) vce(cluster bula)
reghdfe std_var_err U_internal, absorb(bula year) vce(cluster bula)

su var_err, de

clear
cap log close
